<template>
  <div ref="pdfViewer" class="pdf-viewer">
    <h3>pdf</h3>
    <h4>总页数：{{ totalPage }}，当前页：{{ pageNum }}</h4>
    <div ref="pdfWrapper" class="pdf-container"></div>
  </div>
</template>

<script setup>
import * as pdfjsLib from 'pdfjs-dist/build/pdf.mjs'
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs'
// pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://unpkg.com/pdfjs-dist@4.10.38/build/pdf.worker.min.mjs'

const pdfViewer = ref()
const pdfWrapper = ref()
const totalPage = ref(0)
const pageNum = ref(1)
const pdfUrl = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf'
let pdfDoc = null
const scale = 1.4

const renderPage = async (num) => {
  try {
    const page = await pdfDoc.getPage(num)
    const viewport = page.getViewport({ scale })
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = viewport.width
    canvas.height = viewport.height
    pdfWrapper.value.appendChild(canvas)
    const renderContext = {
      canvasContext: context,
      viewport
    }
    await page.render(renderContext).promise
  } catch (err) {
    console.error('渲染页面失败:', err)
  }
}

// 节流函数
const throttle = (func, delay) => {
  let timeoutId
  let lastExecTime = 0
  return function (...args) {
    const currentTime = Date.now()
    
    if (currentTime - lastExecTime > delay) {
      func.apply(this, args)
      lastExecTime = currentTime
    } else {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => {
        func.apply(this, args)
        lastExecTime = Date.now()
      }, delay - (currentTime - lastExecTime))
    }
  }
}

// 滚动事件处理函数
const handleScroll = () => {
  if (!pdfViewer.value) return
  
  const { scrollTop, scrollHeight, clientHeight } = pdfViewer.value
  
  // 检查是否滚动到底部50像素范围内
  if (scrollTop + clientHeight >= scrollHeight - 50) {
    // 如果还有下一页且当前页数小于总页数
    if (pageNum.value < totalPage.value) {
      pageNum.value++
      renderPage(pageNum.value)
    }
  }
}

// 创建节流版本的滚动处理函数（100ms节流）
const throttledHandleScroll = throttle(handleScroll, 100)

// 添加滚动事件监听器
const addScrollListener = () => {
  if (pdfViewer.value) {
    pdfViewer.value.addEventListener('scroll', handleScroll)
  }
}

// 移除滚动事件监听器
const removeScrollListener = () => {
  if (pdfViewer.value) {
    pdfViewer.value.removeEventListener('scroll', handleScroll)
  }
}

const initPdf = async () => {
  const _pdf = await pdfjsLib.getDocument(pdfUrl).promise
  pdfDoc = _pdf
  totalPage.value = _pdf.numPages
  renderPage(1)
}

const renderPdfToContainer = async (container, url, options = {}) => {
  container.innerHTML = ''
  const scale = options?.scale ?? 1.5
  const targetPage = options?.page
  try {
    const loadingTask = pdfjsLib.getDocument(url)
    const pdf = await loadingTask.promise
    const pages = targetPage
      ? [targetPage]
      : Array.from({ length: pdf.numPages }, (_, i) => i + 1)
    for (const pageNum of pages) {
      const page = await pdf.getPage(pageNum)
      const viewport = page.getViewport({ scale })
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      if (!context) continue
      canvas.width = viewport.width
      canvas.height = viewport.height
      
      container.appendChild(canvas)
      const renderContext = {
        canvasContext: context,
        viewport
      }
      await page.render(renderContext).promise
    }

  } catch (err) {
    console.error('PDF 加载失败:', err)
    container.innerHTML = '<p style="color:red">加载失败，请检查文件格式或地址是否正确。</p>'
  }

  // const pdf = await pdfjsLib.getDocument(url).promise
  // const page = await pdf.getPage(1)
  // const viewport = page.getViewport({ scale: options.scale || 1 })
  // const canvas = document.createElement('canvas')
  // const context = canvas.getContext('2d')
  // canvas.height = viewport.height
  // canvas.width = viewport.width
  // await page.render({ canvasContext: context, viewport }).promise
  // container.appendChild(canvas)
}

onMounted(() => {
  // if (pdfWrapper.value) {
  //   renderPdfToContainer(pdfWrapper.value, pdfUrl, { scale: 1.25, page: 1 })
  // }
  initPdf()
  // 添加滚动事件监听器
  nextTick(() => {
    addScrollListener()
  })
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  removeScrollListener()
})
</script>

<style scoped>
.pdf-container {
  width: 100%;
  overflow: auto;
  background: #f6f6f6;
  padding: 16px;
}
.pdf-viewer {
  height: calc(100vh - 80px);
  overflow: scroll;
}
</style>
